package edu.dongthang.server;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import org.apache.xmlbeans.XmlException;
import edu.dongthang.slides.Presentation;

import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;

/**
 * @author thangnd
 * 
 */
public class ServerWindow extends JPanel implements ActionListener {

	private RemoteDataServer server;
	static private final String newline = "\n";
	private Thread sThread; // server thread

	private static final int WINDOW_HEIGHT = 200;
	private static final int WINDOW_WIDTH = 350;
	private static String url;
	private String ipAddress;
	private String noteSlide = "";

	private JFrame window = new JFrame("Remote Slide Server");
	private JMenuBar mb = new JMenuBar();
	private JMenu Menu = new JMenu("File");
	private JMenuItem openFile = new JMenuItem("Open");

	private JLabel addressLabel = new JLabel("");
	private JLabel portLabel = new JLabel("PORT: ");
	private JTextArea[] buffers = new JTextArea[3];
	private JTextField portTxt = new JTextField(5);
	private JLabel serverMessages = new JLabel("Not Connected");

	private JButton connectButton = new JButton("Connect");
	private JButton disconnectButton = new JButton("Disconnect");
	private JFileChooser fc = new JFileChooser();

	public ServerWindow() {
		server = new RemoteDataServer();
		mb.add(Menu);
		Menu.add(openFile);
		openFile.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				int returnVal = fc.showOpenDialog(ServerWindow.this);

				if (returnVal == JFileChooser.APPROVE_OPTION) {
					File file = fc.getSelectedFile();
					url = file.toString();
					System.out.print(url + "\n");
					try {
						noteSlide = getNoteFromeUrl();
						System.out.print(noteSlide);
					} catch (Exception e2) {
						e2.printStackTrace();
					}
					try {
						Desktop.getDesktop().open(file);
					} catch (IOException e1) {
						e1.printStackTrace();
					}
					serverMessages.setText(file.toString() + "." + newline);
				} else {
					serverMessages.setText("Open command cancelled by user."
							+ newline);
				}
			}
		});
		window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.setJMenuBar(mb);

		Image image;
		try {
			image = new ImageIcon(this.getClass().getResource(
					"/images/icon_for_server.png")).getImage();
			window.setIconImage(image);
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		connectButton.addActionListener(this);
		disconnectButton.addActionListener(this);
		fc.setAcceptAllFileFilterUsed(false);
		fc.addChoosableFileFilter(new FileFilter() {

			@Override
			public String getDescription() {
				return "Microsoft Office PowerPoint (*.ppt, *.pptx)";
			}

			@Override
			public boolean accept(File f) {
				if (f.isDirectory()) {
					return true;
				} else {
					return (f.getName().toLowerCase().endsWith(".ppt") || f
							.getName().toLowerCase().endsWith(".pptx"));
				}
			}
		});

		Container c = window.getContentPane();
		c.setLayout(new FlowLayout());

		try {
			InetAddress ip = InetAddress.getLocalHost();
			ipAddress = ip.getHostAddress();
			addressLabel.setText("IP Address: " + ipAddress);
		} catch (Exception e) {
			addressLabel.setText("IP Address Could Not be Resolved");
		}

		int x;
		for (x = 0; x < 3; x++) {
			buffers[x] = new JTextArea("", 1, 30);
			buffers[x].setEditable(false);
			buffers[x].setBackground(window.getBackground());
		}
		c.add(addressLabel);
		c.add(buffers[0]);
		c.add(portLabel);
		portTxt.setText("5444");
		c.add(portTxt);
		c.add(buffers[1]);
		c.add(connectButton);
		c.add(disconnectButton);
		c.add(buffers[2]);
		c.add(serverMessages);

		window.setLocationRelativeTo(null);
		window.setVisible(true);
		window.setResizable(false);
	}

	public void actionPerformed(ActionEvent e) {
		Object src = e.getSource();

		if (src instanceof JButton) {
			if ((JButton) src == connectButton) {
				int port = Integer.parseInt(portTxt.getText());
				runServer(port);
			}

			else if ((JButton) src == disconnectButton) {
				closeServer();
			}
		}
	}

	public void runServer(int port) {
		if (port <= 9999) {
			server.setPort(port);
			sThread = new Thread(server);
			sThread.start();
		} else {
			serverMessages.setText("The port Number must be less than 10000");
		}
	}

	public void closeServer() {
		serverMessages.setText("Disconnected");
		server.shutdown();
		connectButton.setEnabled(true);
	}

	public static void main(String[] args) throws Exception {
		new ServerWindow();
		String processName = "POWERPNT.EXE";

		if (isProcessRunging(processName)) {
			System.out.println("file ppt dang mo");

		} else
			System.out.println("file ppt dang dong");

	}

	private static boolean isProcessRunging(String processName)
			throws Exception {
		Process p = Runtime.getRuntime().exec("tasklist.exe");
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				p.getInputStream()));
		String line;
		while ((line = reader.readLine()) != null) {
			if (line.contains(processName)) {
				return true;
			}
		}
		return false;
	}

	public class RemoteDataServer implements Runnable {
		int PORT;
		private DatagramSocket server;
//		private DatagramPacket servernote;
		private byte[] buf;
		byte[] buf_note = noteSlide.getBytes();
		private DatagramPacket dgp;
		private DatagramPacket note;
		private String message;
		private AutoBot bot;
//		private byte[] buf_note = noteSlide.getBytes();

		public RemoteDataServer(int port) {
			PORT = port;
			buf = new byte[1000];
			if(buf_note != null)
			{
				note = new DatagramPacket(buf_note, buf_note.length);
			}
			dgp = new DatagramPacket(buf, buf.length);
			bot = new AutoBot();
			serverMessages.setText("Not Connected");
		}

		public RemoteDataServer() {
			buf = new byte[1000];
			if(buf_note != null)
			{
				note = new DatagramPacket(buf_note, buf_note.length);
			}
			dgp = new DatagramPacket(buf, buf.length);
			bot = new AutoBot();
			serverMessages.setText("Not Connected");
		}

		public String getIpAddress() {
			String returnStr;
			try {
				InetAddress ip = InetAddress.getLocalHost();
				returnStr = ip.getCanonicalHostName();
			} catch (Exception e) {
				returnStr = new String("Could Not Resolve Ip Address");
			}
			return returnStr;
		}

		public void setPort(int port) {
			PORT = port;
		}

		public void shutdown() {
			try {
				server.close();
				serverMessages.setText("Disconnected");
			} catch (Exception e) {
			}
		}

		public void run() {
			boolean connected = false;
			try {
				InetAddress ip = InetAddress.getLocalHost();
				serverMessages.setText("Waiting for connection on " + ip.getCanonicalHostName());
				server = new DatagramSocket(PORT, ip);
				connected = true;
				connectButton.setEnabled(false);
			} catch (BindException e) {
				serverMessages.setText("Port " + PORT + " is already in use. Use a different Port");
			} catch (Exception e) {
				serverMessages.setText("Unable to connect");
			}

			while (connected) {
				try {
					server.receive(dgp);
					message = new String(dgp.getData(), 0, dgp.getLength());
					if (message.equals("Connectivity")) {
						serverMessages.setText("Trying to Connect");
						server.send(dgp);
					} else if (message.equals("Connected")) {
						server.send(dgp);
					} else if (message.equals("send_note")){
						server.send(note);
						System.out.print("sending note");
					}else if (message.equals("Close")) {
						serverMessages.setText("Controller has Disconnected."+ "Trying to reconnect.");
					} else {
						serverMessages.setText("Connected to Controller");
						bot.handleMessage(message);

					}
				} catch (Exception e) {
					serverMessages.setText("Disconnected");
					connected = false;
				}
			}
		}
	}

	public String getNoteFromeUrl() throws Exception {
		Presentation pre = null;
		String note_slide = "";
		try {
			pre = new Presentation(url);
		} catch (XmlException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String extend = null;
		if (url != null) {
			extend = url.substring(url.lastIndexOf(".") + 1);
		}

		if (extend != null && extend.equalsIgnoreCase("pptx")) {
			try {
				note_slide = pre.getNote_pptx(url);
			} catch (Exception e) {
				// TODO: handle exception
			}
		} else {
			try {
				note_slide = pre.getNote_ppt(url);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		return note_slide;
	}
}
